package com.rybbaby.tss.platform.tags;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;


import com.rybbaby.tss.core.utils.PropertiesReadUtil;
import com.rybbaby.tss.core.utils.StringUtils;
import freemarker.core.Environment;
import freemarker.template.*;

/**
 * @description 资源文件读取标签
 * 
 * @author 谢进伟
 * 
 * @createDate 2016年11月20日 下午11:20:32
 */
public class PropertiesTag extends BodyTagSupport implements TemplateMethodModelEx , TemplateDirectiveModel {
	
	private static final long serialVersionUID = 1L;
	
	/*************************************** 针对freemarker视图的标签实现 ***************************************************/
	@Override
	@SuppressWarnings("rawtypes")
	public Object exec(List arguments) throws TemplateModelException {
		Object key = arguments.get(0);
		if(StringUtils.isNotBlank(key)) {
			String value = PropertiesReadUtil.getStringProperty(key.toString() , "");
			return value;
		} else {
			return "";
		}
	}
	
	@Override
	public void execute(Environment env , Map params , TemplateModel [] loopVars , TemplateDirectiveBody body) throws TemplateException , IOException {
		String key = null;
		Object paramValue = params.get("key");
		if(paramValue instanceof TemplateScalarModel) {
			key = ((TemplateScalarModel)paramValue).getAsString();
		}
		if(body != null) {
			if(StringUtils.isNotBlank(key)) {
				Writer out = env.getOut();
				loopVars[0] = Configuration.getDefaultObjectWrapper(Configuration.getVersion()).wrap(PropertiesReadUtil.getStringProperty(key));
				body.render(out);
			}
		}
	}
	
	/*************************************** 针对jsp视图使的标签实现 ***************************************************/
	/** 资源值key **/
	private String key;
	
	@Override
	public int doAfterBody() throws JspException {
		return super.doAfterBody();
	}
	
	@Override
	public int doEndTag() throws JspException {
		JspWriter out = this.pageContext.getOut();
		try {
			out.print(PropertiesReadUtil.getStringProperty(key.toString() , ""));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doEndTag();
	}
	
	public String getKey() {
		return key;
	}
	
	public void setKey(String key) {
		this.key = key;
	}
	
}
